#ifndef INCL_CPU_H
#define INCL_CPU_H

#include <stdio.h>
#include<fcntl.h>
#include<sys/types.h>
#include<sys/stat.h>
#include<stdlib.h>
#include<unistd.h>

#define MAX_CPU_NUM 8
class cpu
{
public:
    cpu()
        {
            for(int i=0;i<MAX_CPU_NUM;i++)
            {
                last_total_[i]=0;
                last_idle_[i]=0;
                    
            }
        };
    ~cpu(){};
    static cpu *getInstance()
        {
            static cpu ins;
            return &ins;
        }
    int getCpuNum()
    {
        cpunum = sysconf(_SC_NPROCESSORS_CONF);
        return cpunum;
    }

    double getCpurate(int i)
    {
        if(i<=cpunum)
        {
           return percent[i];
        }
    }
    double calCpurate()
    {
        char buf[4096];
	    double total[MAX_CPU_NUM] ;
	    double idle[MAX_CPU_NUM] ;
	    double num = 0;
	    char* buf_ = buf + 3;
	    int fd = open("/proc/stat", O_RDONLY);
	    
        //FILE *fp = fopen("/proc/stat", "r");
        
	    int len = read(fd, buf, sizeof(buf) - 1);
     //   printf("buf size is %d",sizeof(buf));
	    
	    buf_[len] = '\0';
	    total[MAX_CPU_NUM];
        //char* buf_;
        for(int j=0;j<=getCpuNum();j++)
        {
            //fgets(buf,1000,fp);
           // buf[1000]='\0';
           
            
            
            //printf("%s",buf_);
    	    for (int i = 0; i < 20; i++) {
    	      num = strtod(buf_, &buf_);
              //printf("i=%d,j=%d,num=%d\n",i,j,num);
              //printf("%s",buf_);
    	      if (num == 0)
    	        break;
              if(i<=3)
              {
          	      total[j] += num;
              }
    	      if (i == 3)
              {   
    	        idle[j] = num;
                //break;
              }
              if (i ==10)
              {
                break;
              }
    	    }
            percent[j] = 100 * (1 - (idle[j] - last_idle_[j]) / (total[j] - last_total_[j]));
	        last_total_[j] = total[j];
            last_idle_[j] = idle[j];
            //printf("j=%d percent = %d\n",j,percent[j]);
        }
        close(fd);
	    
        
	    return 0; 
    }
    private:
        double last_total_[MAX_CPU_NUM];
        double last_idle_[MAX_CPU_NUM];
        double percent[MAX_CPU_NUM];
        int cpunum;
};







#endif
